package com.xauto.pioneer.appuser.activity.common;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.util.ImageUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.TimeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


public class TakePhotoActivity extends BaseActivity implements View.OnClickListener {
    private Uri imageUri;
    private static final int REQUEST_CAPTURE = 2;
    private static final int REQUEST_PICTURE = 5;
    private static final int RESULT_CROP = 7;
    private static final int GALLERY_ACTIVITY_CODE = 9;
    private TextView fromCarame;
    private TextView fromGarllary;
    private TextView cancelText;
    private Uri localUri = null;
    private String out_path = "";
    View ImageView;
    @Override
    protected int getContentView() {
        return R.layout.ac_take_photo;
    }

    @Override
    protected void initView() {
        ImageView = LayoutInflater.from(mContext).inflate(R.layout.layout_imageview, null);
        TextView TextTime=(TextView)ImageView.findViewById(R.id.texttime);
        TextView TextAdr=(TextView)ImageView.findViewById(R.id.textadr);
        TextView TextDb=(TextView)ImageView.findViewById(R.id.textdb);
        TextTime.setText(TimeUtil.getFormatTime());
        TextAdr.setText(PreferencesUtils.getString(mContext,"ADR"));
        TextDb.setText( PreferencesUtils.getString(mContext,"LNG"));

        fromCarame = (TextView) findViewById(R.id.textview_dialog_take_picture);
        fromCarame.setOnClickListener(this);
        fromGarllary = (TextView) findViewById(R.id.textview_dialog_album);
        cancelText = (TextView) findViewById(R.id.textview_dialog_cancel);
        fromGarllary.setOnClickListener(this);
        cancelText.setOnClickListener(this);
        methodRequiresTwoPermission();
        //拍照提前
        openCamera();
    }

    @Override
    protected void initData() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            imageType = !StringUtils.isBlank(bundle.getString(PARAM_IMAGE_TYPE)) ? bundle.getString(PARAM_IMAGE_TYPE) : DO_SMALL_IMAGE;
            aspectX = bundle.getInt(PARAM_ASPECT_X) != 0 ? bundle.getInt(PARAM_ASPECT_X) : 1;
            aspectY = bundle.getInt(PARAM_ASPECT_Y) != 0 ? bundle.getInt(PARAM_ASPECT_Y) : 1;
            outputX = bundle.getInt(PARAM_OUTPUT_X) != 0 ? bundle.getInt(PARAM_OUTPUT_X) : 360;
            outputY = bundle.getInt(PARAM_OUTPUT_Y) != 0 ? bundle.getInt(PARAM_OUTPUT_Y) : 360;
        }
    }

    @AfterPermissionGranted(1)//添加注解，是为了首次执行权限申请后，回调该方法
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            //已经申请过权限，直接调用相机
            // openCamera();
        } else {
            EasyPermissions.requestPermissions(this, "需要获取权限", 1, perms);
        }
    }

    private void openCamera() {  //调用相机拍照
        //打开拍照或者相册先校验权限问题
        Acp.getInstance(this).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.CAMERA)
                /*以下为自定义提示语、按钮文字
                .setDeniedMessage()
                .setDeniedCloseBtn()
                .setDeniedSettingBtn()
                .setRationalMessage()
                .setRationalBtn()*/
                        .build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent();
                        File file = getOutputMediaFile(); //工具类稍后会给出
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //针对Android7.0，需要通过FileProvider封装过的路径，提供给外部调用
                            imageUri = FileProvider.getUriForFile(mContext, getApplicationContext().getPackageName() + ".provider", file);//通过FileProvider创建一个content类型的Uri，进行封装
                        } else { //7.0以下，如果直接拿到相机返回的intent值，拿到的则是拍照的原图大小，很容易发生OOM，所以我们同样将返回的地址，保存到指定路径，返回到Activity时，去指定路径获取，压缩图片
                            imageUri = Uri.fromFile(file);
                        }
                        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
                        startActivityForResult(intent, REQUEST_CAPTURE);//启动拍照

                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        prompt(permissions.toString() + "权限拒绝");
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CAPTURE:
                    if (imageUri != null) {
                        localUri = imageUri;
                        Bitmap selectedBitmap = ImageUtil.decodeUri(mContext, imageUri, 300, 300);
                        storeImage(ImageUtil.createWaterMaskCenter(selectedBitmap,ImageUtil.convertViewToBitmap(ImageView)));
                        setResult();
//                        performCrop(localUri);
                    }
                    break;
//                case REQUEST_PICTURE:
//                    localUri = data.getData();
//                   performCrop(localUri);
//                    break;
                case RESULT_CROP:
                    Bundle extras = data.getExtras();
                    Bitmap selectedBitmap = extras.getParcelable("data");
                    //判断返回值extras是否为空，为空则说明用户截图没有保存就返回了，此时应该用上一张图，
                    //否则就用用户保存的图
                    if (extras == null) {
                        this.finish();
                    } else {
                        storeImage(ImageUtil.createWaterMaskCenter(selectedBitmap,ImageUtil.convertViewToBitmap(ImageView)));
                        setResult();
                    }
                    break;
//                case GALLERY_ACTIVITY_CODE:
//
//                    localUri = data.getData();
//                    performCrop(localUri);
//                    break;
            }
        }else{
            finish();
        }
    }

    public static final int UPLOAD_SUCCESS = 100;
    public static final int UPLOAD_IMG = 101;

    private void setResult() {
        Intent intent = new Intent();
        intent.putExtra("PATH", out_path);
        setResult(UPLOAD_SUCCESS, intent);
        finish();
    }

    /** 裁剪图片*/
    private void performCrop(Uri uri) {
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                grantUriPermission("com.android.camera", uri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");

            if (Build.MANUFACTURER.contains("HUAWEI")) {//华为特殊处理 不然会显示圆
                intent.putExtra("aspectX", 9998);
                intent.putExtra("aspectY", 9999);
            } else {
                intent.putExtra("aspectX", aspectX);
                intent.putExtra("aspectY", aspectY);
            }
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFile());
            startActivityForResult(intent, RESULT_CROP);
        } catch (ActivityNotFoundException anfe) {
            String errorMessage = "你的设备不支持裁剪行为！";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    /** 建立保存头像的路径及名称*/
    private File getOutputMediaFile() {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + getApplicationContext().getPackageName()
                + "/Files");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        File mediaFile;
        String mImageName ="avatar"+System.currentTimeMillis()+".png";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        out_path = mediaFile.getPath();
        return mediaFile;
    }
    /** 保存图像*/
    private void storeImage(Bitmap image) {
        FileOutputStream fos = null;
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        }
        try {
            fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        }finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textview_dialog_album:
                Intent gallery_Intent = new Intent(Intent.ACTION_PICK, null);
                gallery_Intent.setType("image/*");
                startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
                break;
            case R.id.textview_dialog_take_picture:
                openCamera();
                break;
            case R.id.textview_dialog_cancel:
                finish();
                break;
        }
    }



    /**
     * 图片处理方式：大图使用URI传递，小图使用bitmap传递
     */
    private String imageType = DO_SMALL_IMAGE;
    /**
     * option param key
     */
    public static final String PARAM_IMAGE_TYPE = "IMAGE_TYPE";
    /**
     * option param key-图片宽度比例
     */
    public static final String PARAM_ASPECT_X = "ASPECT_X";
    /**
     * option param key-图片高度比例
     */
    public static final String PARAM_ASPECT_Y = "ASPECT_Y";
    /**
     * option param key-图片宽度
     */
    public static final String PARAM_OUTPUT_X = "OUTPUT_X";
    /**
     * option param key-图片高度
     */
    public static final String PARAM_OUTPUT_Y = "OUTPUT_Y";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_BIG_IMAGE = "DO_BIG_IMAGE";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_SMALL_IMAGE = "DO_SMALL_IMAGE";
    private int aspectX = 1;
    private int aspectY = 1;
    private int outputX = 360;
    private int outputY = 360;

    /***
     * 获取跳转Intent数据
     * @param mContext 上下文
     * @param imageType 图片类型：大图或小图
     * @param aspectX 图片宽度比例
     * @param aspectY 图片高度比例
     * @param outputX 图片宽度
     * @param outputY 图片高度
     * @return
     */
    public static Intent getTakePhotoStartIntent(Context mContext, String imageType,
                                                 int aspectX, int aspectY,
                                                 int outputX, int outputY) {
        Intent intent = new Intent(mContext, TakePhotoActivity.class);
        intent.putExtra(TakePhotoActivity.PARAM_IMAGE_TYPE, imageType);
        intent.putExtra(TakePhotoActivity.PARAM_ASPECT_X, aspectX);
        intent.putExtra(TakePhotoActivity.PARAM_ASPECT_Y, aspectY);
        intent.putExtra(TakePhotoActivity.PARAM_OUTPUT_X, outputX);
        intent.putExtra(TakePhotoActivity.PARAM_OUTPUT_Y, outputY);
        return intent;
    }
}
